package com.icode.lock8;

import java.util.concurrent.TimeUnit;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-10 18:24
 *
 * Q:4
 * 会先打印“方法B”：
 *    两个线程操作不同的对象，A线程执行methodA()时先拿到phone1的锁并执行方法体
 *    B线程执行methodB()时先拿到phone2的锁并执行方法体，由于A方法中睡眠了4秒，
 *    所以B线程先打印
 */
public class  Test3 {
    public static void main(String[] args) {
        Phone3 phone1 = new Phone3();
        Phone3 phone2 = new Phone3();

        new Thread(()->{phone1.methodA();}).start();

        //延时2秒 让线程先拿到锁
        try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}

        new Thread(()->{phone2.methodB();}).start();
    }
}

class Phone3{

    public synchronized void methodA(){
        try {TimeUnit.SECONDS.sleep(4);} catch (InterruptedException e) {e.printStackTrace();}
        System.out.println("方法A");
    }
    public synchronized void methodB(){
        System.out.println("方法B");
    }
}
